package com.whisperly.echotalk.other;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.LocaleList;
import android.preference.PreferenceManager;
import android.text.Html;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.whisperly.echotalk.account.Account;
import com.whisperly.echotalk.bllmodel.ClientClear;
import com.whisperly.echotalk.bllmodel.UserWithChat;
import com.whisperly.echotalk.starryb.schemas.Login;
import com.whisperly.echotalk.starryb.R;
import com.whisperly.echotalk.starryb.utils.AppsManager;
import com.whisperly.echotalk.starryb.utils.DatabaseHelper;
import com.whisperly.echotalk.starryb.utils.GlobalData;
import com.whisperly.echotalk.starryb.utils.Mutual;

import java.util.Locale;
import java.util.Objects;

public class Settings extends AppCompatActivity {
    private LinearLayout page_row1, page_row2, page_row3, page_row4, page_row5, page_row6,page_row_language;
    private Toast currentToast;
    private LinearLayout content, signIn;
    private TextView txtUserName, txtUserID, txtLastTime, tvPrivacyPolicy, tvTermsConditions;
    ;
    private UserWithChat user = new UserWithChat();

    private TextView clock_day;
    @Override
    protected void attachBaseContext(Context newBase) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newBase);
        String languageCode = prefs.getString("language", "en");
        super.attachBaseContext(updateResources(newBase, languageCode));
    }

    public Context updateResources(Context context, String languageCode) {
        Locale locale = new Locale(languageCode);
        Locale.setDefault(locale);

        Resources res = context.getResources();
        Configuration config = new Configuration(res.getConfiguration());
        config.setLocale(locale);
        LocaleList localeList = new LocaleList(locale);
        LocaleList.setDefault(localeList);
        config.setLocales(localeList);
        context = context.createConfigurationContext(config);
        return context;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.x_settings);
        AppsManager.addActivity(this);

        content = findViewById(R.id.content);
        txtUserName = findViewById(R.id.txtUserName);
        txtUserID = findViewById(R.id.txtUserID);
        txtLastTime = findViewById(R.id.txtLastTime);
        clock_day = findViewById(R.id.clock_day);
        signIn = findViewById(R.id.signIn);
        page_row_language = findViewById(R.id.page_row_language);

        SharedPreferences sp = getSharedPreferences("SignUp", MODE_PRIVATE);
        String singUpValue = sp.getString("singUp", "0");
        clock_day.setText(singUpValue);
        if (GlobalData.getUsername() != null && !GlobalData.getUsername().equals("")) {
            content.setVisibility(View.VISIBLE);
            signIn.setVisibility(View.VISIBLE);
            user = GlobalData.getUser();
            txtUserName.setText(user.getName());
            txtUserID.setText(String.valueOf(user.getLoginId()));
            txtLastTime.setText(user.getLoginTime());
        } else {
            content.setVisibility(View.GONE);
            signIn.setVisibility(View.GONE);
        }

        page_row1 = findViewById(R.id.page_row1);
        page_row1.setOnClickListener(v -> {
            Intent intent = new Intent(Settings.this, Account.class);
            startActivity(intent);
        });
        page_row2 = findViewById(R.id.page_row2);
        page_row2.setOnClickListener(v -> {
            if ("".equals(GlobalData.getUsername())) {
                showRegistrationAlertDialog();
            } else {
                Intent intent = new Intent(Settings.this, Records.class);
                startActivity(intent);
            }
        });
        page_row3 = findViewById(R.id.page_row3);
        page_row3.setOnClickListener(v -> {
            Intent intent = new Intent(Settings.this, ClientClear.class);
            startActivity(intent);
        });

        page_row4 = findViewById(R.id.page_row4);
        page_row4.setOnClickListener(v -> {
            Intent intent = new Intent(Settings.this, FeedBack.class);
            startActivity(intent);
        });
        page_row5 = findViewById(R.id.page_row5);
        page_row5.setOnClickListener(v -> {
            if (currentToast != null) {
                currentToast.cancel();
            }

            currentToast = Toast.makeText(this, R.string.It_is_currently_the_latest_version, Toast.LENGTH_SHORT);
            currentToast.show();
        });
        page_row6 = findViewById(R.id.page_row6);
        page_row6.setOnClickListener(v -> {
            Intent intent = new Intent(this, About.class);
            startActivity(intent);
//            overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
        });

        page_row_language.setOnClickListener(v -> showChangeLanguageDialog());

        tvPrivacyPolicy = findViewById(R.id.tv_privacy_policy);

        tvTermsConditions = findViewById(R.id.tv_terms_conditions);

        tvPrivacyPolicy.setText(Html.fromHtml(getString(R.string.Privacy), Html.FROM_HTML_MODE_LEGACY));
        tvTermsConditions.setText(Html.fromHtml(getString(R.string.Terms_and_Conditions), Html.FROM_HTML_MODE_LEGACY));


        tvPrivacyPolicy.setOnClickListener(v -> {
            showPrivacyPolicy();
        });

        tvTermsConditions.setOnClickListener(v -> {
            showTermsConditions();
        });

    }

    private void showRegistrationAlertDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.login_is_required)
                .setMessage(R.string.login_is_required_message)
                .setPositiveButton(R.string.login, (dialog, which) -> {
                    dialog.dismiss();
                    Intent intent = new Intent(this, Login.class);
                    startActivity(intent);
                    AppsManager.finishAll();
                }).setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss()).setCancelable(false)
                .show();
    }

    private void showPrivacyPolicy() {
        Intent intent = new Intent(this, Mutual.class);
        intent.putExtra("str1", "https://blinkchat-privacy.chen88.top");
        intent.putExtra("str2", "Privacy Policy");
        startActivity(intent);
    }

    private void showTermsConditions() {
        Intent intent = new Intent(this, Mutual.class);
        intent.putExtra("str1", "https://blinkchat-privacy.chen88.top/terms-condition.html");
        intent.putExtra("str2", "User Agreement");
        startActivity(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        SharedPreferences sp = getSharedPreferences("SignUp", MODE_PRIVATE);
        String singUpValue = sp.getString("singUp", "0");
        clock_day.setText(singUpValue);
    }

    public void changeLanguage(String languageCode) {

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        prefs.edit().putString("language", languageCode).apply();

        Intent i = getBaseContext().getPackageManager()
                .getLaunchIntentForPackage(getBaseContext().getPackageName());
        Objects.requireNonNull(i).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(i);
    }

    public void showChangeLanguageDialog() {
        final String[] languageItems = {"English", "中文"};
        final String[] languageCodes = {"en", "zh"};

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.language_settings)
                .setItems(languageItems, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        changeLanguage(languageCodes[which]);
                    }
                });
        AlertDialog dialog = builder.create();
        dialog.show();
    }
}
